package cn.anjubao.cp.api.pay;

import cn.anjubao.cp.api.common.Constants;
import cn.anjubao.cp.api.dto.unifiedPayReqForm;
import cn.anjubao.cp.api.entity.ParkingRecord;
import cn.anjubao.cp.api.entity.TradeOrder;
import cn.anjubao.cp.api.feign.PaymentFeignClient;
import cn.anjubao.cp.api.mapper.ParkingRecordMapper;
import cn.anjubao.cp.api.mapper.TradeOrderMapper;
import cn.anjubao.cp.api.pay.utils.PayUtils;
import cn.anjubao.cp.api.pay.vo.PayNotifyVo;
import cn.anjubao.cp.common.base.exception.BusinessException;
import com.anjubao.parking.municipal.common.dto.ApiResult;
import com.anjubao.parking.municipal.payment.dto.BalancePayDto;
import com.anjubao.parking.municipal.payment.dto.OrderResponseDto;
import com.anjubao.parking.municipal.payment.dto.PayResponseDto;
import com.anjubao.parking.municipal.payment.form.BalanceRechargeForm;
import com.anjubao.parking.municipal.payment.form.SubmitOrderForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.ZoneId;
import java.util.Date;

@Service
public class PaymentService {

    private static final Logger logger = LoggerFactory.getLogger(PaymentService.class);

    @Autowired
    private PaymentFeignClient paymentFeignClient;
    @Autowired
    private TradeOrderMapper tradeOrderMapper;
    @Autowired
    private ParkingRecordMapper parkingRecordMapper;
    @Autowired
    private PayUtils payUtils;


    /**
     * 余额支付
     * @param reqForm
     * @param tradeOrder
     * @param type 1：低杆缴费 2:中杆预缴 3：中杆补缴
     * @throws BusinessException
     */
    public void blancePay(unifiedPayReqForm reqForm, TradeOrder tradeOrder, int type) throws BusinessException {
        tradeOrderMapper.insert(tradeOrder);
        ParkingRecord parkingRecord=parkingRecordMapper.selectById(tradeOrder.getParkingRecordId());
        SubmitOrderForm orderForm=new SubmitOrderForm();
        orderForm.setParkingLotSlotName(parkingRecord.getSlotNum());
        orderForm.setVehicle(parkingRecord.getVehicleNumber());
        orderForm.setRemoteParkingRecordId(parkingRecord.getId());
        orderForm.setUserCode(reqForm.getUserCode());
        orderForm.setBusinessId(tradeOrder.getId());
        orderForm.setOrderType(1);
        orderForm.setPayChannelId(4);
        orderForm.setTotalFee(reqForm.getAmount());
        orderForm.setParkingLotName(parkingRecord.getParkingLotName());
        ApiResult<OrderResponseDto> apiResult=paymentFeignClient.submitOrder(1,orderForm);
        if(apiResult.getCode()!=2000  || apiResult.getResult().getBalancePayDto().getResultCode()==2){
            throw new BusinessException("-1",apiResult.getDesc());
        }
        BalancePayDto resPayDto=apiResult.getResult().getBalancePayDto();
        Date payTime=Date.from(resPayDto.getPayTime().atZone(ZoneId.systemDefault()).toInstant());
        if (resPayDto.getResultCode()==1){//余额支付成功
            if(type== Constants.lowPolePay){
                payUtils.handlePayCallBack(tradeOrder,payTime,Constants.lowPolePay,Constants.balancePay);
            }
            if (type==Constants.middlePoleFixPay){
                payUtils.handlePayCallBack(tradeOrder,payTime,Constants.middlePoleFixPay,Constants.balancePay);
            }
            if (type == Constants.middlePolePrePay) {
                payUtils.handlePayCallBack(tradeOrder,payTime,Constants.middlePolePrePay,Constants.balancePay);
            }
        }

    }

    /**
     * 在线支付
     * @param reqForm
     * @param tradeOrder
     * @param type 1：低杆缴费 2:中杆预缴  3：中杆补缴  4：充值
     * @return
     */
    public PayResponseDto onLinePay(unifiedPayReqForm reqForm, TradeOrder tradeOrder, int type)throws BusinessException{
        tradeOrderMapper.insert(tradeOrder);
        ParkingRecord parkingRecord=parkingRecordMapper.selectById(tradeOrder.getParkingRecordId());
        if (type==Constants.rechargePay){
            BalanceRechargeForm chargeForm=new BalanceRechargeForm();
            chargeForm.setUserCode(reqForm.getUserCode());
            chargeForm.setBusinessId(tradeOrder.getId());
            chargeForm.setTotalFee(reqForm.getAmount());
            ApiResult<PayResponseDto> apiResult=paymentFeignClient.balanceRecharge(chargeForm);
            if (apiResult.getCode()!=2000){
                throw new BusinessException("-1",apiResult.getDesc());
            }
            return apiResult.getResult();
        }else {
            SubmitOrderForm orderForm=new SubmitOrderForm();
            orderForm.setParkingLotSlotName(parkingRecord.getSlotNum());
            orderForm.setVehicle(parkingRecord.getVehicleNumber());
            orderForm.setRemoteParkingRecordId(parkingRecord.getId());
            orderForm.setUserCode(reqForm.getUserCode());
            orderForm.setBusinessId(tradeOrder.getId());
            orderForm.setPayChannelId(1);
            orderForm.setTotalFee(reqForm.getAmount());
            orderForm.setParkingLotName(parkingRecord.getParkingLotName());
            if (type==Constants.lowPolePay)orderForm.setOrderType(1);
            if (type==Constants.middlePolePrePay|| type==Constants.middlePoleFixPay)orderForm.setOrderType(2);
            ApiResult<OrderResponseDto> apiResult=paymentFeignClient.submitOrder(1,orderForm);
            if (apiResult.getCode()!=2000){
                throw new BusinessException("-1",apiResult.getDesc());
            }
            return apiResult.getResult().getPayment();
        }
    }


    /**
     * 微信支付回调处理
     * @param vo
     */
    public  void doPayNotify( PayNotifyVo vo){
        TradeOrder tradeOrder=tradeOrderMapper.selectById(vo.getBusinessId());
        if (tradeOrder==null){
            logger.info("无该下单记录！！！");
            return;
        }
        if(tradeOrder!=null && tradeOrder.getOrderState()==1){
            logger.info("该下单记录已支付,重复支付！！！tradeOrderId:{}",tradeOrder.getId());
            return;
        }
        //一、低杆缴费
        if (tradeOrder.getOrderType()==2){
            payUtils.handlePayCallBack(tradeOrder,vo.getPayTime(),Constants.lowPolePay,Constants.onLinePay);
        }
        //二、中杆补缴
        if(tradeOrder.getOrderType()==3  && tradeOrder.getPayType()==2){
            payUtils.handlePayCallBack(tradeOrder,vo.getPayTime(),Constants.middlePoleFixPay,Constants.onLinePay);
        }
        //三、中杆预缴
        if (tradeOrder.getOrderType()==3 && tradeOrder.getPayType()==1){
            payUtils.handlePayCallBack(tradeOrder,vo.getPayTime(),Constants.middlePolePrePay,Constants.onLinePay);
        }
        //四、余额充值
        if (tradeOrder.getOrderType()==1){
            payUtils.handlePayCallBack(tradeOrder,vo.getPayTime(),Constants.rechargePay,Constants.onLinePay);
        }
    }


}
